package com.xjrsoft.module.interfaceManager.service.impl;

import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjrsoft.core.secure.XjrUser;
import com.xjrsoft.core.secure.utils.SecureUtil;
import com.xjrsoft.core.tool.utils.CollectionUtil;
import com.xjrsoft.core.tool.utils.StringPool;
import com.xjrsoft.module.interfaceManager.entity.XjrInterfaceAuth;
import com.xjrsoft.module.interfaceManager.mapper.XjrInterfaceAuthMapper;
import com.xjrsoft.module.interfaceManager.service.IXjrInterfaceAuthService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 接口权限表 服务实现类
 * </p>
 *
 * @author tzx
 * @since 2022-04-22
 */
@Service
public class XjrInterfaceAuthServiceImpl extends ServiceImpl<XjrInterfaceAuthMapper, XjrInterfaceAuth> implements IXjrInterfaceAuthService {

    @Override
    public boolean checkAuth(String infoId, HttpServletRequest request) {
        XjrUser user = SecureUtil.getUser();
        String isWorkFlow = request.getHeader("isWorkFlow");
        if (BooleanUtil.toBoolean(isWorkFlow) || user.isAdminUser()) {
            return true;
        }
        String[] roleIds = StringUtils.split(user.getRoleId(), StringPool.COMMA);
        int count = this.count(Wrappers.<XjrInterfaceAuth>query().lambda().eq(XjrInterfaceAuth::getInfoId, infoId)
                .and(userWrapper -> userWrapper.eq(XjrInterfaceAuth::getObjectId, user.getUserId()).eq(XjrInterfaceAuth::getObjectType, 2)
                        .or(roleWrapper -> roleWrapper.eq(XjrInterfaceAuth::getObjectType, 1).in(roleIds != null && roleIds.length > 0, XjrInterfaceAuth::getObjectId, roleIds))));
        return count > 0;
    }

    @Override
    public List<String> getAuthIdsOfObject(String objectId, Integer objectType) {
        return this.baseMapper.getAuthIdsOfObject(objectId, objectType);
    }
}
